package com.tanhua.server.service;



import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 圈子  朋友圈
 */
@Service
public class MovementsService {

   /* @Autowired
    private UserService userService;*/
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    /**
     * 发布动态
     * @param textContent  动态文本
     * @param location      坐标位置
     * @param longitude     经度
     * @param latitude      纬度
     * @param multipartFiles  上传的文件数组
     * @param
     * @return
     */
    public String saveMovements(String textContent,
                                 String location,
                                 String longitude,
                                 String latitude,
                                MultipartFile[] multipartFiles) {
        //获取当前登录用户
        User user = UserThreadLocal.get();
        /*if (null==user){
            return false;
        }*/

        //创建动态信息对象
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        //图片 上传
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            //上传文件,返回上传结果
            PicUploadResult uploadResult = this.picUploadService.upload(multipartFile);
            imageUrls.add( uploadResult.getName());
        }
        //把上传后的图片路径储存到"动态信息对象中"
        publish.setMedias(imageUrls);

        //保存
        return  this.quanZiApi.savePublish(publish);
    }

    /**
     * 动态列表
     * @param user  当前用户,如果为null,则查询"推荐动态"
     * @param page
     * @param pageSize  每页显示个数
     * @return
     */
    private PageResult queryPublishList(User user,Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        Long userId = null;//默认查询推荐动态
        PageInfo<Publish> pageInfo = null;

        if(null == user){
            //查询推荐动态
            String key = "QUANZI_PUBLISH_RECOMMEND_" +UserThreadLocal.get().getId();
            String value = this.redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(value)){
                //命中了数据
                String[] pids = StringUtils.split(value,',');
                int startIndex = (page - 1) * pageSize;
                if (startIndex <pids.length) {
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pids.length){
                        endIndex = pids.length-1;
                    }
                    List<Long> pidList = new ArrayList<>();
                    for (int i = 0; i <= pids.length; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }
                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(publishList);
                }
            }
        }

        //如果没有查询到推荐
        if (pageInfo == null){
            //默认查询逻辑
            if (user != null){//如果用户id不为null,则表示有用户,则查询的是"用户好友的动态信息"
                //查询好友动态
                userId=user.getId();
            }
            pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);

        }

        //查询完成后,依然需要获取当前的登录用户
        user = UserThreadLocal.get();

        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        List<Publish> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            //没有查询到动态数据
            return pageResult;
        }

        pageResult.setItems(this.fillValueToMovements(records));

       /* List<Movements> movementsList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());
            //如果不包含则添加
            if (!userIds.contains(record.getUserId())) {
                userIds.add(record.getUserId());
            }
            movements.setLoveCount(100); //TODO 喜欢数
            movements.setLikeCount(80); //TODO 点赞数
            movements.setDistance("1.2公里"); //TODO 距离
            movements.setHasLoved(1); //TODO 是否喜欢
            movements.setHasLiked(0); //TODO 是否点赞
            movements.setCommentCount(30); //TODO 评论数
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated()))); //发布时间，10分钟前
            movements.setTextContent(record.getText());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));

            movementsList.add(movements);
        }
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userInfoQueryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue()==userInfo.getUserId().longValue()){
                    movements.setTags(StringUtils.split(userInfo.getTags(),','));
                    movements.setNickname(userInfo.getNickName());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setAge(userInfo.getAge());
                    break;
                }
            }
        }
        pageResult.setItems(movementsList);*/
        return pageResult;
    }


    private List<Movements> fillValueToMovements(List<Publish> records){
        User user = UserThreadLocal.get();
        List<Movements> movementsList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());
            if (!userIds.contains(record.getUserId())){
                userIds.add(record.getUserId());
            }
            String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLiked(this.redisTemplate.hasKey(likeUserCommentKey)?1:0);//是否点赞

            String likeCommentKey = "QUANZI_COMMENT_LIKE_" + movements.getId();
            String value = this.redisTemplate.opsForValue().get(likeCommentKey);
            if (StringUtils.isNotEmpty(value)){
                movements.setLikeCount(Integer.valueOf(value));//点赞数
            }else {
                movements.setLikeCount(0);//点赞数
            }

            String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLoved(this.redisTemplate.hasKey(loveUserCommentKey)?1:0);//是否喜欢
            String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveValue = this.redisTemplate.opsForValue().get(loveCommentKey);
            if (StringUtils.isNotEmpty(loveValue)){
                movements.setLoveCount(Integer.valueOf(loveCommentKey));//喜欢数
            }else{
                movements.setLoveCount(0);//喜欢数为0
            }
            movements.setDistance("1.2公里"); //TODO 距离
            movements.setCommentCount(30); //TODO 评论数
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated()))); //发布时间，10分钟前
            movements.setTextContent(record.getText());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));

            movementsList.add(movements);
        }
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userInfoQueryWrapper);

        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {

                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));
                    movements.setNickname(userInfo.getNickName());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setAge(userInfo.getAge());

                    break;
                }
            }
        }

        return movementsList;
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null,page,pageSize);
    }
    public PageResult queryUserPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(UserThreadLocal.get(),page,pageSize);
    }




    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!bool) {
            //保存失败
            return null;
        }
        //保存成功,获取点赞数
        Long likeCunt=0L;
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        if (!this.redisTemplate.hasKey(likeCommentKey)){
            Long count = this.quanZiApi.queryCommentCount(publishId, 1);
            likeCunt=count;
            this.redisTemplate.opsForValue().set(likeCommentKey,String.valueOf(likeCunt));
        }else{
            this.redisTemplate.opsForValue().increment(likeCommentKey);
        }

        //记录当前已经点赞
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey,"1");
        return likeCunt;
    }

    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!bool) {
            return null;
        }
        //redis中的点赞数需要减少1
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommentKey);
        //删除该用户的标记点赞
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommentKey);
        return count;
    }

    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!bool) {
            //保存失败
            return null;
        }
        //保存成功
        Long loveCount = 0L;
        String loverCommentKey = "QUANZI_COMMENT_LOVE_"+publishId;
        if (!this.redisTemplate.hasKey(loverCommentKey)){
            Long aLong = this.quanZiApi.queryCommentCount(publishId, 1);
            loveCount=aLong;
            this.redisTemplate.opsForValue().set(loverCommentKey,String.valueOf(loveCount));
        }else{
            loveCount = this.redisTemplate.opsForValue().increment(loverCommentKey);
        }
        //记录当前已将喜欢的
        String likeUserCommentKey = "QUANZI_COMMENT_LOVE_USER_"+user.getId()+"_"+publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey,"1");
        return loveCount;
    }

    public Long nuLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!bool){
            return null;
        }
        //redis中的喜欢数需要减少1
        String likeCommentKey = "QUANZI_COMMENT_LOVE_"+publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommentKey);

        //删除该用户的喜欢标记
        String likeUserCommentKey = "QUANZI_COMMENT_LOVE_USER_"+user.getId()+"_"+publishId;
        this.redisTemplate.delete(likeUserCommentKey);
        return count;
    }

    public Movements queryMovementsById(String publishId) {

        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (null==publish) {
            return null;
        }

        //查询到动态数据，数据的填充
        List<Movements> movementsList = this.fillValueToMovements(Arrays.asList(publish));
        return movementsList.get(0);
    }

    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        String redisKey = "visitor_date_"+user.getId();

        //如果redis中存在上次查询的时间,就按照这个时间之后查询,如果没有就查询前3个
        List<Visitors> visitors = null;
        String value = this.redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(value)){
            visitors = this.visitorsApi.topVisitor(user.getId(), 3);
        }else {
             visitors = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(value));
        }
        if (CollectionUtils.isEmpty(visitors)){
            return Collections.emptyList();
        }
        List<Long> userIds = new ArrayList<>();
        for (Visitors visitor : visitors) {
            userIds.add(visitor.getVisitorUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryList(queryWrapper);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        Map<Long,UserInfo> userInfoMap = new HashMap<>();
        for (UserInfo userInfo : userInfoList) {
            userInfoMap.put(userInfo.getUserId().longValue(),userInfo);
        }
        for (Visitors visitor : visitors) {
            UserInfo userInfo = userInfoMap.get(visitor.getVisitorUserId().longValue());
            VisitorsVo visitorsVo = new VisitorsVo();
            visitorsVo.setAge(userInfo.getAge());
            visitorsVo.setAvatar(userInfo.getLogo());
            visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
            visitorsVo.setId(userInfo.getUserId());
            visitorsVo.setNickname(userInfo.getNickName());
            visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
            visitorsVo.setFateValue(visitor.getScore().intValue());
            visitorsVoList.add(visitorsVo);
            break;
        }
        return visitorsVoList;
      }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            return pageResult;
        }

        pageResult.setItems(this.fillValueToMovements(records));
        return pageResult;
    }
}
